package model;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URLClassLoader;

import controller.PlateformeCore;

import interfaces.IPlateFormeAPI;
import interfaces.IPlateformePlugin;

public class LazyPlugin implements IPlateformePlugin {

	private IPlateformePlugin realPlugin;
	private String nameRealPlugin;
	private URLClassLoader url;
	
	public LazyPlugin(String s, URLClassLoader u){
		this.nameRealPlugin=s;
		this.url=u;
	}
	
	@Override
	public String getNamePlugin() {
		// TODO Auto-generated method stub
		this.checkRealPlugin();
		return realPlugin.getNamePlugin();
	}
	
	@Override
	public void load() {
		// TODO Auto-generated method stub
		this.checkRealPlugin();
		realPlugin.load();
	}
	
	public Object getRealPlugin(){
		return realPlugin;
	}
	
	private void checkRealPlugin(){
		if(realPlugin==null){
			try {
				for(Constructor<?> c : Class.forName(this.nameRealPlugin,false,url).getConstructors()){
					if(c.getParameterTypes().length==1 && IPlateFormeAPI.class.isAssignableFrom(c.getParameterTypes()[0])){
						realPlugin = (IPlateformePlugin) c.newInstance(PlateformeCore.papi);
						return;
					}
				}
				realPlugin = (IPlateformePlugin) Class.forName(this.nameRealPlugin,false,url).newInstance();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return;
	}
}
